package com.serialPort.web.controller;

import com.fazecast.jSerialComm.SerialPort;
import com.serialPort.web.service.ASTMMessageService;
import com.serialPort.web.service.SerialPortService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class SerialPortController {

    @Value("${lisapi.com}")
    private String comValue;

    @Value("${lisapi.baudrate}")
    private Integer baudrate;

    @Autowired
    private SerialPortService serialPortService;

    @Autowired
    private ASTMMessageService astmMessageService;

    private static SerialPortController serialPortController;


    @PostConstruct
    private void init() {
        serialPortController = this;
        serialPortController.comValue = comValue;
        serialPortController.baudrate = baudrate;
        serialPortController.serialPortService = serialPortService;
        serialPortController.astmMessageService = astmMessageService;
    }


    public void run() {
        SerialPort[] ports = SerialPort.getCommPorts();
        for (SerialPort port : ports) {
            log.info("设备所有串口: " + port.getSystemPortName());
        }
        log.info("设备串口设置为：" + serialPortController.comValue + "，波特率：" + serialPortController.baudrate);
        for (SerialPort port : ports) {
            if (port.getSystemPortName().equals(serialPortController.comValue)) {
                log.info("开始监听串口：" + serialPortController.comValue);
                serialPortController.astmMessageService.startASTMListener(port);
            }
        }
    }
}
